package com.martin.dms.dataservices.hib;

import java.util.List;

import org.hibernate.Session;

import com.martin.dms.dataservices.PurchaseDataService;
import com.martin.dms.model.Purchase;
import com.martin.dms.model.hib.PurchaseHib;

/**
 * Hibernate implementation of the Purchase data service.
 * 
 * @author mtsvetkov.
 */
public class PurchaseDataServiceHib implements PurchaseDataService {

    private static final String PURCHASE_GET_ALL_QUERY = "Purchase.getAll";

    private Session session;

    /**
     * Constructor that expects a hibernate session.
     * 
     * @param session - the current hibernate session.
     */
    public PurchaseDataServiceHib(Session session) {
        this.session = session;
    }

    /**
     * {@inheritDoc}
     */
    public Purchase create(Purchase dmsObject) {
        PurchaseHib purchase = new PurchaseHib();
        purchase.setClient(dmsObject.getClient());
        purchase.setItem(dmsObject.getItem());
        purchase.setAmount(dmsObject.getAmount());
        purchase.setDate(dmsObject.getDate());
        session.save(purchase);
        return purchase;
    }

    /**
     * {@inheritDoc}
     */
    public void delete(long id) {
        PurchaseHib purchase = get(id);
        session.delete(purchase);
    }

    /**
     * {@inheritDoc}
     */
    public PurchaseHib get(long id) {
        return (PurchaseHib) session.get(PurchaseHib.class, Long.valueOf(id));
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    public List<Purchase> getAll() {
        return session.getNamedQuery(PURCHASE_GET_ALL_QUERY).list();
    }

}
